from typing import Dict
from x_com.import_api import ecommerce_data_source_service_0_0_1
from utils import time_utils

class UserLoginDataAnalyzer:
    # 当前在线的人数
    online_num: int
    # 年度数据
    class YearData:
        # 每月增加的用户
        monthly_active_num_dict: Dict[int, int]
        # 按小时分布的用户
        # 0~12
        hour_active_num_dict: Dict[int, int]
        def __init__(self):
            self.monthly_active_num_dict = {}
            self.hour_active_num_dict = {}
    # key 为 年份
    year_data_dict : Dict[int, YearData]

    def __init__(self):
        self.online_num = 0
        self.year_data_dict = {}
        
    def data_in(self, param: ecommerce_data_source_service_0_0_1.UserLoginInfo):
        if param.is_login:
            self.online_num += 1
        else:
            self.online_num -= 1
            # 防止在线人数为 负数
            if self.online_num < 0:
                self.online_num = 0

        datetime_obj = time_utils.str_to_datetime(param.handle_time)
        # 数据所在的年份
        year = datetime_obj.year
        # 年数据
        if year not in self.year_data_dict:
            self.year_data_dict[year] = self.YearData()

        year_data = self.year_data_dict[year]
        month = datetime_obj.month
        # 
        if param.is_login:
            # 用户登录就是活跃的数据了
            if month not in year_data.monthly_active_num_dict:
                year_data.monthly_active_num_dict[month] = 1
            else:
                year_data.monthly_active_num_dict[month] += 1
            # 按两个小时划分一个时间段
            hour_segment = int(datetime_obj.hour / 2) 
            if hour_segment not in year_data.hour_active_num_dict:
                year_data.hour_active_num_dict[hour_segment] = 1
            else:
                year_data.hour_active_num_dict[hour_segment] += 1

    def get_online_num(self) -> int:
        return self.online_num
    
    def get_data_by_year(self, year: int) -> YearData:
        return self.year_data_dict.get(year)